/**
   communication_queue.cu - Created by Timothy Morey on 8/11/2011.

 */

#include <pthread.h>
#include <queue>

#include "communication_queue.h"
#include "message.h"

CommunicationQueue::CommunicationQueue()
{
  pthread_mutex_init(&_Mutex, 0);
}

CommunicationQueue::~CommunicationQueue()
{
  pthread_mutex_destroy(&_Mutex);
}

void CommunicationQueue::Push(MessagePtr msg)
{
  if(this->GetLock())
  {
    _Queue.push(msg);
    this->ReleaseLock();
  }
}

void CommunicationQueue::Push(Message* msg)
{
  MessagePtr ptr(msg);
  this->Push(ptr);
}

MessagePtr CommunicationQueue::Pop()
{
  MessagePtr retval;

  if(this->GetLock())
  {
    if(! _Queue.empty())
    {
      retval = _Queue.front();
      _Queue.pop();
    }

    this->ReleaseLock();
  }

  return retval;
}

bool CommunicationQueue::GetLock()
{
  return 0 == pthread_mutex_lock(&_Mutex);
}

void CommunicationQueue::ReleaseLock()
{
  pthread_mutex_unlock(&_Mutex);
}
